package com.youdianstar.app.ui.help

import android.text.Editable
import android.text.TextWatcher
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.databinding.ActivityReportFeedbackBinding
import com.youdianstar.app.entity.FeedbackReq
import com.youdianstar.app.ui.ReportResultActivity

import com.youdianstar.app.common.*
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.entity.FileUpResult
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.EditUtil
import com.youdianstar.app.common.util.LogUtil
import com.youdianstar.app.common.util.StrUtil
import com.youdianstar.app.common.util.dialog.DialogUtil
import com.youdianstar.app.common.widget.adapter.MultiPicAdapter
import com.youdianstar.app.common.auko.startActivity
import org.koin.androidx.viewmodel.ext.android.viewModel
import com.google.common.base.Joiner

/**
 * File: FeedbackActivity
 * Author: 82149 Create: 2021/12/1 14:13
 * Changes (from 2021/12/1)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class FeedbackActivity :BaseActivity<ActivityReportFeedbackBinding,FeedbackViewModel>(){
    override fun layoutId(): Int = R.layout.activity_report_feedback

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): FeedbackViewModel {
        val model : FeedbackViewModel by viewModel()
        return model
    }

    /**
     * 业务类型: 0- 普通feedback,13-Buy PB,15-Swapping
     */
    var bisType: Int = 0
    /**置换与购买PB 流水单号*/
    var billOrderNo: String? = null
    /**购买PB 是否退款*/
    var isRefund: Boolean = false

    //图片选择
    private var selectType: Int = 0
    var picAdapter: MultiPicAdapter? = null
    var imageList = mutableListOf<String>()

    //问题多选拼接
    lateinit var boxImageList : List<ImageView>
    lateinit var clickLayoutList : List<LinearLayout>
    //选中内容 下标
    var selectIndex = -1

    override fun initViewLayout() {
        super.initViewLayout()
        mBinding.headBar.initTitle(this, getString(R.string.help_feedback))//help_fb

        EditUtil.setEditSpaceFilter(mBinding.edtContent)
        mBinding.edtContent.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                mBinding.tvCount.text = "${s.toString().length ?: 0}/300"
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }
        })
    }

    override fun initData() {
        super.initData()
        if(bisType==0){
            bisType = intent.getIntExtra(Extra.IT_TYPE,0)
        }
        initImageAction()

        boxImageList = listOf(
            mBinding.bxFunction,mBinding.bxSuggestion, mBinding.bxOthers
        )
        clickLayoutList = listOf(
            mBinding.llFunction,mBinding.llSuggestion, mBinding.llOthers
        )
        LogUtil.i("----Feedback bisType=$bisType ;orderNo = $billOrderNo,isRefund = $isRefund")
    }

    override fun initClickEvent() {
        clickLayoutList.forEach {
            it.setOnClickListener { lay->
                //多选模式
                for ((index, v) in clickLayoutList.withIndex()) {
                    if (v.id == lay.id){
                        selectIndex = index
                    }
                }
                refreshBoxUI(selectIndex.toString())
            }
        }

        mBinding.btnConfirm.setThrottleListener {
            //点击上报
            if (selectIndex==-1){
                toastShow(getString(R.string.toast_selOption))
                return@setThrottleListener
            }

            val etEmail = mBinding.edtEmail.text.toString().trim()
            if (StrUtil.isEmpty(etEmail)){
                toastShow(getString(R.string.toast_requiredEmail))
                return@setThrottleListener
            }

            if (!StrUtil.emailFormat(etEmail)){
                toastShow(getString(R.string.toast_validEmail))
                return@setThrottleListener
            }

            val etText = mBinding.edtContent.text.toString().trim()
            if (StrUtil.isEmpty(etText)){
                toastShow(getString(R.string.help_inputFBContent))
                return@setThrottleListener
            }

            if (bisType!=0 && imageList.isEmpty()){
                toastShow(getString(R.string.toast_requiredPhoto))
                return@setThrottleListener
            }

            //反馈类型 1-功能异常 2-建议优化 3-2分钟内正常归还 4-其他反馈
            var reportType = 0
            when(selectIndex){
                0-> reportType = 1
                1-> reportType = 2
                2-> reportType = 4
            }
            mViewModel.reportFeedback(FeedbackReq(etText,etEmail,Joiner.on(",").join(imageList),reportType))
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.fileDeleteLiveData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
            }
        })

        mViewModel.fileUpLoadLiveData.observe(this,object : BaseApiResultObserver<FileUpResult>(false){
            override fun onDataResult(data: FileUpResult?) {
                super.onDataResult(data)
                dismissDialog()
                data?.let {
                    LogUtil.i("----add ="+it.value)
                    imageList.add(it.value)
                    picAdapter?.refreshData(imageList)
                    mBinding.tvPicCount.text = imageList.size.toString()+"/3"
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })

        mViewModel.reportResultLiveData.observe(this,object : BaseApiResultObserver<Any>(true){
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                startActivity<ReportResultActivity>(Extra.IT_TYPE to BisType.Report_Feedback)
                finish()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })

    }

    /**
     * 设置CheckBox样式
     * @param selected 选择状态
     */
    private fun refreshBoxUI(selected :String){
        for ((index, image) in boxImageList.withIndex()){
            image.setImageResource(if (selected == index.toString()) R.mipmap.box_single_selected else R.mipmap.box_single_unselected)
        }
        for ((index, lg) in clickLayoutList.withIndex()){
            lg.setBackgroundResource(if (selected == index.toString()) R.drawable.bg_report_selected else R.drawable.bg_report_unselected)
        }
    }

    private fun initImageAction() {
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        mBinding.rcyPic.layoutManager = linearLayoutManager

        picAdapter = MultiPicAdapter(this, 3, mutableListOf<String>(), object : MultiPicAdapter.OnPicSelect {
            override fun onAdd() {
                showPhotoDialog()
            }

            override fun onDelete(index: Int) {
                if (imageList.isEmpty().not() && index <= imageList.size - 1) {
                    mViewModel.deleteImage(imageList[index])
                    imageList.removeAt(index)
                    picAdapter?.refreshData(imageList)
                    mBinding.tvPicCount.text = imageList.size.toString()+"/3"
                }
            }
        })
        mBinding.rcyPic.adapter = picAdapter
    }


    /************************************图片选择部分***********************************/

    /**
     * 图片选择器
     */
    private fun showPhotoDialog() {
        DialogUtil.instance.showSelectDialog(this) { selectIndex ->
            selectType = selectIndex
            when (selectIndex) {
                PHOTO_CAMERA -> requestCameraPermission {
                    showPhotoPicker(PHOTO_CAMERA)
                }
                PHOTO_ALBUM -> requestAlbumPermission {
                    showPhotoPicker(PHOTO_ALBUM)
                }
            }
        }
    }

    /**
     * 调用-ImagePicker
     * @param type
     */
    private fun showPhotoPicker(type: Int) {
        startSLImagePicker(this, type = type, needCrop = false) { path ->
            mViewModel.upLoadImage(path)
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        super.onPermissionsGranted(requestCode, perms)
        if (requestCode == REQUEST_PERMISSION_CODE)
            showPhotoPicker(selectType)
    }
}